/**
 * 
 */
package com.scpii.universal.resource;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.scpii.universal.generator.Generator;
import com.scpii.universal.util.StreamUtil;

/**
 * UniversalApi
 * 
 * @author 甘建新 2012-7-13上午11:35:14
 */
@Controller
@RequestMapping("/Handler")
public class Handler {

	@Resource
	private Generator generator;

	private Logger log = Logger.getLogger(Handler.class);

	/**
	 * 以GET方式访问
	 * 
	 * @param cmd
	 * @param data
	 * @author 甘建新 2012-7-13下午02:09:40
	 */
	@RequestMapping(method = RequestMethod.GET, produces = { "application/octet-stream" })
	public void executeGET(@RequestParam("cmd") Integer cmd,
			@RequestParam("data") String data, HttpServletRequest request,
			HttpServletResponse response) {
		log.info("执行了GET方法，传递的参数为：" + cmd + "," + data);
		if ((cmd != null && cmd >= 0)
				&& (data != null && data.trim().length() > 0)) {
			byte[] dataBytes = data.getBytes();
			// 得到后台取到的数据
			byte[] returnData = generator.startGenerate(cmd, dataBytes);
			// 传输数据
			StreamUtil.transData(returnData, response);
		}
	}

	/**
	 * 以POST方式访问（默认访问方式为POST）
	 * 
	 * @param cmd
	 * @author 甘建新 2012-7-13下午02:09:49
	 */
	@RequestMapping(method = RequestMethod.POST, produces = { "application/octet-stream" })
	public void executePOST(@RequestParam("cmd") Integer cmd,
			HttpServletRequest request, HttpServletResponse response) {
		log.info("执行了POST方法,传递的参数为：" + cmd);
		long startTime = System.currentTimeMillis();
		if (cmd != null && cmd >= 0) {
			try {
				// 获得通过POST方式传的字节流
				byte[] dataBytes = StreamUtil.convertToBytes(request
						.getInputStream());
				log.info("传入数据大小为："
						+ (dataBytes != null ? dataBytes.length : 0));
				// 取到后台返回的数据
				byte[] returnData = generator.startGenerate(cmd, dataBytes);
				log.info("传出数据大小为："
						+ (returnData != null ? returnData.length : 0));
				// 传输数据
				long endTime = System.currentTimeMillis();
				response.setHeader("REPLAY", (startTime - endTime) + "");
				StreamUtil.transData(returnData, response);
			} catch (Exception e) {
				e.printStackTrace();
				log.error("异常", e);
			}
		}
	}

}
